<template>
  <rui-page :defines="defines">
    <div>
      <Alert show-icon style="height: 30px;">
        <div style="margin-top:-2px">请输入查询条件</div>
      </Alert>
      <rui-query ref="searchForm" :query="queryData" :query-rows="searchFormLabels" />
    </div>
    <div class="search">
      <Row class="operation">
        <Col>
        <Card>
          <Row class="operation">
            <Button type="primary" @click="delBtn">删除</Button>
            <Button type="primary" @click="editBtn">编辑</Button>
            <Button type="primary" @click="addRuleBtn">新增</Button>
          </Row><br>
          <Row>
            <Alert show-icon>
              已选择 <span class="select-count">{{selectCount}}</span> 项
              <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
          </Row>
          <rui-table :loading="loading" border :defineId="'reviewRulesId'" @loadDatas="queryData" :showIndex="false" :select="true" :columns="columns" :data="data" :slots="[{key:'isEnable',slot:'isEnable'}]" @on-selection-change="changeSelect" @on-sort-change="changeSort" ref-query="searchForm" ref="rulesTable">
            <template slot="isEnable" slot-scope="{ row }">
              <div>
                <Button v-if="row.isEnable==='no'" style="margin-right:5px" @click="openRule(row)" size="small" type="primary" icon="ios-create">启用</Button>
                <Button v-if="row.isEnable==='yes'" style="margin-right:5px" @click="closeRule(row)" size="small" type="error" icon="md-trash">停用</Button>
                  <Button type="primary" @click="createRules(row)">配置复核规则</Button>
              </div>
            </template>
          </rui-table>
          <Modal v-model="activateVisible" :title="activateTitle" :closable="true" :mask-closable='true' :width="1000" :styles="{top: '180px'}">
            <Row>
              <rui-form :form-options="formOptions" :label-width="150" :read-only="false" ref="showForm" />
            </Row>
            <div slot="footer">
              <Button size="small" @click="activateVisible = false">取消</Button>
              <Button size="small" @click="saveRule">保存</Button>
            </div>
          </Modal>
          <Modal v-model="rulesVisible" :title="ruleTitle" :closable="false" :mask-closable='false' :width="1000" :styles="{top: '180px'}">
            <Row>
              <rule-tree v-if="dataLoad" :rule-data="ruleData" :ruleAtoms="ruleAtoms" :ruleName="ruleName" :ruleGroup="ruleGroup" :businessScenario="businessScenario" @saved="updateRuleId" :rule-id="rule_Id" />
            </Row>
            <div slot="footer">
              <Button size="small" @click="rulesVisible = false,dataLoad = false">取消</Button>
            </div>
          </Modal>
        </Card>
        </Col>
      </Row>
    </div>
  </rui-page>
</template>
<script>
import loanReviewRuleDefine from '../defines/loan-review-rule-define'
import {
  getLoanReviewRuleList,
  addRule,
  editRule,
  delByIds,
  openRuleById,
  closeRuleById,
  updateRuleId,
} from '_p/afs-core-business/api/afs-case/loan-review-rule/loanReviewRule'
import ruiRules from '_c/rui-auto/rui-rules/index'
import { queryAtomsByBizType } from '@/projects/basic/api/rule/ruleAtom'
import { loadRuleDataById } from '_p/basic/api/rule/rule'

export default {
  name: 'loan-review-rule',
  components: {
    ruleTree: ruiRules,
  },
  data() {
    return {
      loading: true,
      modalTitle: '',
      ruleTitle: '',
      activateTitle: '',
      activateVisible: false,
      rulesVisible: false,
      modalType: 0, // 判断是添加还是修改
      selectCount: 0,
      drop: false,
      data: [],
      total: 0,
      searchFormLabels: [
        {
          defineId: 'reviewRulesId',
          span: 8,
          fields: [
            'reviewName',
            'ruleDesc',
            'isEnable',
            'createBy',
            'effectTime',
            'failureTime',
          ],
        },
      ],
      formOptions: [
        {
          grids: [
            {
              defineId: 'reviewRulesId',
              span: 8,
              fields: ['reviewNameDisplay', 'ruleDescDisplay'],
            },
          ],
        },
      ],
      columns: [
        'isEnable',
        'reviewNo',
        'reviewName',
        'ruleDesc',
        'effectTime',
        'failureTime',
        'ruleId',
      ],
      ruleAtoms: [],
      ruleTree: [],
      fitScope: 'loanReviewRule',
      path: 'case',
      ruleName: '复核规则配置',
      ruleGroup: 'reviewRuleGroup',
      businessScenario: 'businessScenario',
      dataLoad: false,
      ruleData: [],
      rule_Id: null,
      row: {},
    }
  },
  computed: {
    defines() {
      return [{ id: 'reviewRulesId', fields: loanReviewRuleDefine }]
    },
  },
  methods: {
    refresh() {
      this.$refs['rulesTable'].reloadData()
    },
    queryData(queryData) {
      // 多条件搜索用户列表
      this.loading = true
      getLoanReviewRuleList(queryData).then((res) => {
        if (res.code === '0000') {
          let { records, total } = res.data
          this.$refs.rulesTable.updateTableData(records, total)
        }
      })
      queryAtomsByBizType(this.fitScope, this.path).then((res) => {
        if (res.code === '0000') {
          this.ruleAtoms = res.data
        }
      })
    },
    createRules(row) {
        if (row.isEnable === 'yes') {
          this.$Message.warning('不可操作已启用的规则')
          return
        }
        this.row=row;
      this.$refs.showForm.resetFrom()
      if (row.ruleId && row.ruleId != '') {
        loadRuleDataById(row.ruleId, this.path).then((res) => {
          if (res.code === '0000') {
            if (res.data.length > 0) {
              this.ruleData = res.data
            }
            this.dataLoad = true
            this.rule_Id = row.ruleId
          }
        })
      } else {
        this.rule_Id = null
        this.ruleData = []
        this.dataLoad = true
      }
      this.businessScenario = row.id
      this.ruleTitle = '复核规则配置'
      this.row = row
      this.rulesVisible = true
    },
    editBtn() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未选择要编辑的数据')
        return
      } else if (this.selectCount > 1) {
        this.$Message.warning('请勾选单条数据进行编辑操作')
        return
      }
      this.dataLoad = true
      this.modalType = 1 //编辑状态
      this.activateTitle = '编辑规则描述'
      let row
      this.selectList.forEach((e) => {
        row = e
        row.reviewNameDisplay = e.reviewName
        row.ruleDescDisplay = e.ruleDesc
      })
      this.$refs.showForm.updateFormData(row)
      this.$refs.showForm.setAllFieldRequired(true)
      this.activateVisible = true
    },
    addRuleBtn() {
      this.modalType = 0 //新增状态
      this.$refs.showForm.resetFrom()
      this.$refs.showForm.setAllFieldRequired(true)
      this.activateTitle = '新增复核规则'
      this.activateVisible = true
    },
    saveRule() {
      this.$refs.showForm.getForm().validate((valid) => {
        if (valid) {
          let param = this.$refs.showForm.getFormData()
          param.reviewName = param.reviewNameDisplay
          param.ruleDesc = param.ruleDescDisplay
          if (this.modalType === 0) {
            //默认生效
            param.isEnable = 'no'
            addRule(param)
              .then((res) => {
                if (res.code === '0000') {
                  this.$Message.success(res.msg)
                  this.refresh()
                  this.activateVisible = false
                }
              })
              .catch(() => {
                this.refresh()
              })
          } else {
            // 编辑
            editRule(param)
              .then((res) => {
                if (res.code === '0000') {
                  this.$Message.success(res.msg)
                  this.refresh()
                  this.activateVisible = false
                }
              })
              .catch(() => {
                this.refresh()
              })
          }
        }
      })
    },
    delBtn() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未选择要删除的数据')
        return
      }
      let ids = []
      let rules = false
      this.selectList.forEach((e) => {
        if (e.isEnable === 'yes') {
          rules = true
          return
        }
        ids += e.id + ','
      })
      if (rules) {
        this.$Message.warning('不可操作已启用的规则')
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        content: '您确认要删除所选的 ' + this.selectCount + ' 条数据?',
        onOk: () => {
          ids = ids.substring(0, ids.length - 1)
          delByIds(ids).then((res) => {
            if (res.code === '0000') {
              this.$Message.success(res.msg)
              this.clearSelectAll()
              this.refresh()
            }
          })
        },
      })
    },
    clearSelectAll() {
      this.$refs.rulesTable.getTable().selectAll(false)
    },
    changeSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    changeSort(e) {
      this.searchForm.sort = e.key
      this.searchForm.order = e.order
      if (e.order === 'normal') {
        this.searchForm.order = ''
      }
      this.refresh()
    },
    openRule(row) {
      if (!row.ruleId || row.ruleId == '') {
        this.$Message.warning('您还未配置规则无法启用该条规则.')
        return
      }
      this.$Modal.confirm({
        title: '确认启用',
        content: '您确认要启用规则【' + row.reviewName + '】?',
        onOk: () => {
          openRuleById(row.id).then((res) => {
            if (res.code === '0000') {
              this.$Message.success(res.msg)
              this.refresh()
            }
          })
        },
      })
    },
    closeRule(row) {
      this.$Modal.confirm({
        title: '确认停用',
        content: '您确认要停用规则【' + row.reviewName + '】?',
        onOk: () => {
          closeRuleById(row.id).then((res) => {
            if (res.code === '0000') {
              this.$Message.success(res.msg)
              this.refresh()
            }
          })
        },
      })
    },
    updateRuleId(ruleId) {
        this.row.ruleId=ruleId;
        updateRuleId(this.row)
          .then((res) => {
            if (res.code === '0000') {
              this.$Message.success(res.msg)
              this.refresh()
              this.rulesVisible = false
              this.dataLoad = false
            }
          })
          .catch(() => {
            this.refresh()
          })
    },
  },
  mounted() {
    this.refresh()
  },
}
</script>
